package com.yuexun.beilunpatient.ui.family.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.yuexun.beilunpatient.R;
import com.yuexun.beilunpatient.base.BaseEntity;
import com.yuexun.beilunpatient.base.BaseKJActivity;
import com.yuexun.beilunpatient.config.AppConfig;
import com.yuexun.beilunpatient.ui.bean.BaseListEntity;
import com.yuexun.beilunpatient.ui.family.adapter.FamilyListAdapter;
import com.yuexun.beilunpatient.ui.family.bean.KinsfolkBean;
import com.yuexun.beilunpatient.ui.family.model.impl.FamilyModel;
import com.yuexun.beilunpatient.ui.family.presenter.impl.FamilyListPresenter;
import com.yuexun.beilunpatient.ui.family.ui.view.IFamilyListView;
import com.yuexun.beilunpatient.ui.registration.bean.AppointmentLoginBean;
import com.yuexun.beilunpatient.ui.registration.model.impl.RegistrationModel;
import com.yuexun.beilunpatient.ui.registration.presenter.impl.AppointmentLoginPresenter;
import com.yuexun.beilunpatient.ui.registration.ui.Act_Appointment_Auth;
import com.yuexun.beilunpatient.ui.registration.ui.Act_Appointment_Register;
import com.yuexun.beilunpatient.ui.registration.ui.view.IAppointmentLoginView;
import com.yuexun.beilunpatient.widget.EmptyLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.beilunpatient.widget.PullToRefresh.PullToRefreshList;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by chenss on 2018/10/26.
 */
public class Act_Family_List extends BaseKJActivity implements IFamilyListView, IAppointmentLoginView {

    @Bind(R.id.content_list)
    PullToRefreshList contentList;
    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.ll_add)
    LinearLayout llAdd;
    @Bind(R.id.edit)
    TextView edit;
    @Bind(R.id.delete)
    TextView delete;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_ids)
    TextView tvIds;
    @Bind(R.id.tv_phone)
    TextView tvPhone;

    FamilyListAdapter adapter;
    ListView listView;
    List<KinsfolkBean> datas = new ArrayList<>();
    boolean isDo;

    FamilyListPresenter listPresenter;
    AppointmentLoginPresenter loginPresenter;

    @Override
    public void setRootView() {
        setContentView(R.layout.act_family_list);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        listPresenter = new FamilyListPresenter(new FamilyModel(), this);
        loginPresenter = new AppointmentLoginPresenter(new RegistrationModel(), this);

        tvName.setText(PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_NAME));
        tvIds.setText("身份证号：" + PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ID_CARD));
        initList();
//        if (getIntent().getExtras().getString("type").equals("2")) {
//            tvPhone.setText("手机号：" + PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.PHONE));
//            ApiGetData();
//        }else{
//            autoLogin();
//        }
        autoLogin();
    }

    private void ApiGetData() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("memberNum", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUM));
        params.put("accessToken", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCESSTOKEN));
        params.put("type", "1");
        listPresenter.getAppoinmentFamilyNum(params);
    }

    private void autoLogin() {
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));
        loginPresenter.appointmentLogin(params);
    }

    /**
     * 初始化列表
     */
    private void initList() {
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                ApiGetData();
            }
        });

        listView = contentList.getRefreshView();
        listView.setOverScrollMode(ListView.OVER_SCROLL_NEVER);
        contentList.setPullRefreshEnabled(true);
        contentList.setPullLoadEnabled(false);
        ((FooterLoadingLayout) contentList.getFooterLoadingLayout()).setNoMoreDataText("无更多数据");

        adapter = new FamilyListAdapter(listView, datas, R.layout.item_family);
        listView.setAdapter(adapter);

        contentList.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                ApiGetData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
//                nowpage = nowpage + 1;
//                ApiGetData();
            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (getIntent().getExtras().getString("type").equals("2")) {
                    Bundle bundle = new Bundle();
                    Intent intent = new Intent();
                    bundle.putString("name", datas.get(i).getName());
                    bundle.putString("memberNum", datas.get(i).getMember_num_proxy());
                    bundle.putString("idCard", datas.get(i).getIdcard());
                    intent.putExtras(bundle);
                    setResult(10000, intent);
                    finish();
                }
            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        ApiGetData();
    }

    @OnClick({R.id.title_back, R.id.ll_add, R.id.edit, R.id.delete, R.id.ll_self})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ll_self:
                if (getIntent().getExtras().getString("type").equals("2")) {
                    Bundle bundle = new Bundle();
                    Intent intent = new Intent();
                    bundle.putString("name", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.USER_NAME));
                    bundle.putString("memberNum", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUM));
                    bundle.putString("idCard", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ID_CARD));
                    intent.putExtras(bundle);
                    setResult(10000, intent);
                    finish();
                }
                break;
            case R.id.ll_add:
                Intent intent = new Intent(aty, Act_Family_Add.class);
                startActivity(intent);
                break;
            case R.id.edit:
                if (isDo) {
                    adapter.setSelect(false);
                    edit.setText("解绑");
                    delete.setVisibility(View.GONE);
                    llAdd.setVisibility(View.VISIBLE);
                } else {
                    adapter.setSelect(true);
                    edit.setText("取消");
                    delete.setVisibility(View.VISIBLE);
                    llAdd.setVisibility(View.GONE);
                }
                isDo = !isDo;
                break;
            case R.id.delete:
                List<String> pmIds = new ArrayList<>();
                for (KinsfolkBean beanDate : datas) {
                    if (beanDate.isSelect()) {
                        pmIds.add(beanDate.getPatientRelativeId());
                    }
                }
                if (pmIds.size() > 0) {
                    ApiForKjHttp(pmIds);
                } else {
                    ViewInject.toast("请选择要解绑的亲属号");
                }
                break;
        }
    }

    private void ApiForKjHttp(List<String> pmIds) {
        String BaseUrl = AppConfig.WEB_SYSTEM + "deletePatientRelative.json?";
        String partUrl = "";
        for (int i = 0; i < pmIds.size(); i++) {
            partUrl = partUrl + "patientRelativeIds=" + pmIds.get(i) + "&";
        }
        if (partUrl != null && partUrl.length() > 0) {
            partUrl = partUrl.substring(0, partUrl.length() - 1);
        }
        BaseUrl = BaseUrl + partUrl;

        KJHttp client = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("memberNum", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.MEMBENUM));
        params.put("accessToken", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.ACCESSTOKEN));
        params.put("sessionUuidPatient", PreferenceHelper.readString(aty, AppConfig.USER_INFO, AppConfig.SESSION_ID));

        client.post(BaseUrl, params, new HttpCallBack() {
            @Override
            public void onSuccess(String t) {
                super.onSuccess(t);
                BaseListEntity baseBean = JSON.parseObject(t, BaseListEntity.class);
                if (baseBean.getStatus().equals("200")) {
                    ViewInject.toast("解绑成功");
                    ApiGetData();
                } else {
                    ViewInject.toast("解绑失败");
                }
            }

            @Override
            public void onFailure(int errorNo, String strMsg) {
                super.onFailure(errorNo, strMsg);
                Toast.makeText(aty, "解绑失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void getAppoinmentFamilyNum(BaseEntity<KinsfolkBean> baseEntity) {
        if (contentList.isPullRefreshEnabled()) {
            contentList.onPullDownRefreshComplete();
        }
        if (baseEntity.getStatus().equals("200")) {
            datas.clear();
            datas = baseEntity.getDatas();
            adapter.refresh(datas);

        } else {
            ViewInject.toast(baseEntity.getMessage());
        }

        if (datas.size() == 0) {
            emptyLayout.setErrorType(EmptyLayout.NODATA);
        } else {
            emptyLayout.dismiss();
        }
    }

    @Override
    public void deletePatientRelative(BaseEntity<String> baseEntity) {
        if (baseEntity.getStatus().equals("200")) {
            ApiGetData();
        }
    }

    @Override
    public void appointmentLogin(BaseEntity<AppointmentLoginBean> baseEntity) {
        if (baseEntity.getStatus().equals("200")) {
            AppointmentLoginBean loginBean = baseEntity.getDatas().get(0);
            if (loginBean.getRegisterState() == 0) {
                String filename = AppConfig.USER_INFO;
                PreferenceHelper.write(aty, filename, AppConfig.ACCESSTOKEN, loginBean.getAccessToken());
                PreferenceHelper.write(aty, filename, AppConfig.MEMBENUM, loginBean.getMembeNum());
                PreferenceHelper.write(aty, filename, AppConfig.ISREGISTRATIONLOGIN, true);
                PreferenceHelper.write(aty, filename, AppConfig.PHONE, loginBean.getPhone());

                tvPhone.setText("手机号：" + loginBean.getPhone());
                ApiGetData();
            } else if (loginBean.getRegisterState() == 1) {
                Intent intent = new Intent(aty, Act_Appointment_Register.class);
                startActivity(intent);
            } else if (loginBean.getRegisterState() == 2) {
                Bundle bundle = new Bundle();
                bundle.putString("phone", loginBean.getPhone());
                Intent intent = new Intent(aty, Act_Appointment_Auth.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }
    }
}
